﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ZX.DAL.DBExtend;
using System.Data.SqlClient;
using ZX.SYS.Library;

namespace ZX.SYS.Bussiness.DeskTop
{
    public class BDeskTop
    {
        #region 
        /// <summary>
        /// 获取所有 桌面模板表
        /// </summary>
        /// <returns></returns>
        public static List<SysDesktopTemplate> GetDeskTopTemplateList(string RoleID)
        {
            BSysDesktopTemplate bll = new BSysDesktopTemplate();
            return (List<SysDesktopTemplate>)bll.GetDeskTopTemplateList(RoleID);
        }
        /// <summary>
        /// 编辑 桌面模板表
        /// </summary>
        /// <returns></returns>
        public static bool ModifyDeskTopTemplate(SysDesktopTemplate entity, string modifyType = "add")
        {
            bool isSave = false;
            BSysDesktopTemplate bll = new BSysDesktopTemplate();
            if (modifyType == "add") isSave = bll.Insert(entity);
            else isSave = bll.Update(entity);

            return isSave;
        }
        /// <summary>
        /// 根据编号获取桌面模板对象
        /// </summary>
        /// <param name="DeskTopTempID"></param>
        /// <returns></returns>
        public static SysDesktopTemplate GetSysDesktopTemplateEntity(string DeskTopTempID, string RoleID)
        {
            BSysDesktopTemplate bll = new BSysDesktopTemplate();
            SysDesktopTemplate entity = bll.GetSysDesktopTemplateEntity(DeskTopTempID, RoleID);
            if (entity == null) entity = bll.GetSysDesktopTemplateEntity2(DeskTopTempID);
            return entity;
        }
        /// <summary>
        /// 删除 桌面模板表
        /// </summary>
        /// <returns></returns>
        public static bool DeleteDeskTopTemplate(string DeskTopTempID)
        {
            BSysDesktopTemplate bll = new BSysDesktopTemplate();
            return bll.DeleteysDesktopTemplate(DeskTopTempID);
        }

        #endregion

        #region 桌面角色

        /// <summary>
        /// 根据编号获取角色桌面对象
        /// </summary>
        /// <param name="DeskTopTempID"></param>
        /// <returns></returns>
        public static SysRoleDesktop GetRoleDesktopEntity(string RoleDesktopID)
        {
            string sql = @"
                        select 
                        b.RoleDesktopID,
                        a.DeskTopTempID,
                        a.DeskTopTempName
                        ,a.Src
                        ,case when b.Height is null then a.Height else b.Height end as Height
                        ,a.PageType
                        ,case when b.PowerType is null then a.PowerType else b.PowerType end as PowerType
                        ,a.TabTools
                        ,a.Region
                        ,b.Sort
                        ,b.RoleId,a.More
                        ,b.PowerType from SysDesktopTemplate a,SysRoleDesktop b 
                        where a.DeskTopTempID=b.DeskTopTempID and b.RoleDesktopID='@RoleDesktopID'";

            sql = sql.Replace("@RoleDesktopID", RoleDesktopID);
            DbSql execsql = new DAL.DBExtend.DbSql();
            DataTable dsGetSysUserDesktop = execsql.ExecuteQuery(sql);

            if (dsGetSysUserDesktop.Rows.Count > 0)
            {
                SysRoleDesktop r = new SysRoleDesktop
                {
                    RoleDesktopID = new Guid(dsGetSysUserDesktop.Rows[0]["RoleDesktopID"].ToString()),
                    DeskTopTempID = new Guid(dsGetSysUserDesktop.Rows[0]["DeskTopTempID"].ToString()),
                    DeskTopName = dsGetSysUserDesktop.Rows[0]["DeskTopTempName"].ToString(),
                    Src = dsGetSysUserDesktop.Rows[0]["Src"].ToString(),
                    Height = dsGetSysUserDesktop.Rows[0]["Height"].ToString(),
                    PageType = int.Parse(dsGetSysUserDesktop.Rows[0]["PageType"].ToString()),
                    PowerType = int.Parse(dsGetSysUserDesktop.Rows[0]["PowerType"].ToString()),
                    Region = dsGetSysUserDesktop.Rows[0]["Region"].ToString(),
                    RoleId = new Guid(dsGetSysUserDesktop.Rows[0]["RoleId"].ToString()),
                    Sort = int.Parse(dsGetSysUserDesktop.Rows[0]["Sort"].ToString()),
                    TabTools = dsGetSysUserDesktop.Rows[0]["TabTools"].ToString(),
                    More = dsGetSysUserDesktop.Rows[0]["More"].ToString(),
                };
                return r;
            }
            return null;
        }

        /// <summary>
        /// 获取 角色桌面表
        /// </summary>
        /// <param name="RoleID"></param>
        /// <returns></returns>
        public static List<SysRoleDesktop> GetSysRoleDesktopList(string RoleID)
        {
            string sql = @"
                        select 
                        b.RoleDesktopID,
                        a.DeskTopTempID,
                        a.DeskTopTempName
                        ,a.Src
                        ,case when b.Height is null then a.Height else b.Height end as Height
                        ,a.PageType
                        ,case when b.PowerType is null then a.PowerType else b.PowerType end as PowerType
                        ,a.TabTools
                        ,a.Region
                        ,b.Sort,a.More
                        ,b.RoleId
                        from SysDesktopTemplate a,SysRoleDesktop b 
                        where a.DeskTopTempID=b.DeskTopTempID and b.RoleId='@RoleID'";

            sql = sql.Replace("@RoleID", RoleID);
            DbSql execsql = new DAL.DBExtend.DbSql();
            DataTable dsGetSysUserDesktop = execsql.ExecuteQuery(sql);

            var list = new List<SysRoleDesktop>();
            foreach (DataRow row in dsGetSysUserDesktop.Rows)
            {
                SysRoleDesktop r = new SysRoleDesktop
                {
                    RoleDesktopID = new Guid(row["RoleDesktopID"].ToString()),
                    DeskTopTempID = new Guid(row["DeskTopTempID"].ToString()),
                    DeskTopName = row["DeskTopTempName"].ToString(),
                    Src = row["Src"].ToString(),
                    Height = row["Height"].ToString(),
                    PageType =Convert.ToInt32(row["PageType"].ToString()),
                    PowerType = Convert.ToInt32(row["PowerType"].ToString()),
                    Region = row["Region"].ToString(),
                    RoleId = new Guid(row["RoleId"].ToString()),
                    Sort =Convert.ToInt32(row["Sort"].ToString()),
                    TabTools = row["TabTools"].ToString(),
                    More = row["More"].ToString(),
                };
                list.Add(r);
            }
            return list;
        }

        /// <summary>
        /// 保存角色对应胡桌面数据
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string ModifySysRoleDeskTop(List<SysRoleDesktop> list)
        {
            StringBuilder sbSql = new StringBuilder();
            string returnText = string.Empty;

            int indexRow = -1;
            string notInDeskTopTempID = string.Empty;
            DbSql execsql = new DAL.DBExtend.DbSql();
            SqlParameter[] sqlparams1 = new SqlParameter[]{
                    new SqlParameter("@RoleID",SqlDbType.VarChar,100)
                 };
            sqlparams1[0].Value = list[0].RoleId.ToString();

            DataSet dsGetSysUserDesktop = execsql.RunProcedure("sp_GetSysUserDesktop", sqlparams1, true);

            SqlParameter[] sqlparams2 = new SqlParameter[]{
                    new SqlParameter("@RoleID",SqlDbType.VarChar,100)
                 };
            sqlparams2[0].Value = list[0].RoleId.ToString();
            string delSql = execsql.RunProcedureReturnString("sp_SetSysRoleDesktop", sqlparams2, out indexRow);
            string tempDeskTopName = "初始化数据ABC,";
            if (dsGetSysUserDesktop != null && dsGetSysUserDesktop.Tables[0].Rows.Count > 0)
            {
                returnText += "以下桌面数据无法处理：\n";
                foreach (DataRow row in dsGetSysUserDesktop.Tables[0].Rows)
                {
                    bool isContionus = false;
                    string[] temp = tempDeskTopName.Split(',');
                    for (int i = 0; i < temp.Length-1; i++) if (temp[i] == row["DeskTopName"].ToString()) isContionus = true;
                    if (isContionus) continue;
                    tempDeskTopName += row["DeskTopName"].ToString() + ",";
                    returnText += "[" + row["DeskTopName"].ToString() + "] ";
                    DataRow[] myrow=dsGetSysUserDesktop.Tables[0].Select("DeskTopName='"+ row["DeskTopName"].ToString()+"'");
                    foreach (DataRow dr in myrow)
                    {
                        //returnText += "\n\t正在被用户 [" + dr["UName"].ToString() + "] \n\t";
                        notInDeskTopTempID += "'" + dr["DeskTopTempID"].ToString() + "',";
                    }
                    returnText += "有用户正在使用\n";
                }
                notInDeskTopTempID = notInDeskTopTempID.Substring(0, notInDeskTopTempID.Length - 1);
            }

            bool isAddHeadInsertSql = false;
            bool CanRun = false;
            string insertSql = "insert into SysRoleDesktop(RoleDesktopID,DeskTopTempID,DeskTopName,Src,Height,RoleId,Sort) ";
            foreach (SysRoleDesktop model in list)
            {
                if (notInDeskTopTempID.IndexOf(model.DeskTopTempID.ToString().Trim()) > 0)
                    continue;
                CanRun = true;
                if (!isAddHeadInsertSql) sbSql.Append(insertSql);

                string src=model.Src;
                string height=model.Height;
                string selectSql =string.Empty;
                if (src != null && src.Length > 0)
                    selectSql += "select '" + Guid.NewGuid() + "' as RoleDesktopID,DeskTopTempID,DeskTopTempName,'" + src + "',";
                else
                    selectSql += "select '" + Guid.NewGuid() + "' as RoleDesktopID,DeskTopTempID,DeskTopTempName,Src,";

                if (height != null && height.Length > 0)
                    selectSql += "'" + height + "',";
                else
                    selectSql += "Height,";

                selectSql +="'" + model.RoleId + "' as RoleId," + model.Sort + " as Sort from SysDesktopTemplate where DeskTopTempID='" + model.DeskTopTempID + "' union ";
                sbSql.Append(selectSql);
                isAddHeadInsertSql = true;
            }

            string excSql = sbSql.ToString();
            if (excSql.Trim().EndsWith("union"))
                excSql = excSql.Substring(0, excSql.Length - 6);
            int update = -1;
            if (CanRun) update = execsql.ExecuteSqlTran(excSql);
            if (update >= 0) returnText += "\n\n其他数据操作完成\n\t";
            return returnText;
        }

        #endregion
    }
}
